package com.beiben.utils.excel;

import com.ruoyi.common.config.RuoYiConfig;
import java.io.File;
import java.io.IOException;
import java.util.UUID;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.metadata.Font;
import com.alibaba.excel.metadata.Sheet;
import com.alibaba.excel.metadata.TableStyle;
import com.alibaba.excel.support.ExcelTypeEnum;
import org.apache.poi.ss.usermodel.IndexedColors;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Excel导出工具类
 *
 * @author 熊国强
 * @date 2020-11-19
 */
public class ExcelUtils {



    /**
     * 下载EXCEL文件2007版本
     *
     * @throws IOException IO异常
     */
    public static void exportExcel2007Format(EasyExcelParams excelParams) throws IOException {
        exportExcel(excelParams, ExcelTypeEnum.XLSX);
    }

    /**
     * 下载EXCEL文件2003版本
     *
     * @throws IOException IO异常
     */
    public static void exportExcel2003Format(EasyExcelParams excelParams) throws IOException {
        exportExcel(excelParams, ExcelTypeEnum.XLS);
    }

    /**
     * 根据参数和版本枚举导出excel文件
     *
     * @param excelParams 参数实体
     * @param typeEnum    excel类型枚举
     * @throws IOException
     */
    private static void exportExcel(EasyExcelParams excelParams, ExcelTypeEnum typeEnum) throws IOException {
        HttpServletResponse response = excelParams.getResponse();
        ServletOutputStream out = response.getOutputStream();

        // ExcelWriter提供了多种构造方式，可自行查看选择所需要的
        ExcelWriter writer = new ExcelWriter(null, out, typeEnum,true, excelParams.getWriteHandler());

        // 设置web下载等的信息
        prepareResponds(response, typeEnum);
        // 创建一个sheet
        Sheet sheet = new Sheet(1, 0, excelParams.getDataModelClazz());
        sheet.setSheetName(excelParams.getSheetName());

        // 设置列宽 设置每列的宽度
        Map<Integer,Integer> columnWidth = new HashMap<>(6);
        columnWidth.put(0,6666);
        columnWidth.put(1,5000);
        columnWidth.put(2,15000);
        columnWidth.put(3,3000);
        columnWidth.put(4,20000);
        columnWidth.put(5,10000);
        sheet.setColumnWidthMap(columnWidth);
        sheet.setAutoWidth(Boolean.TRUE);
        // 用于设置 表格样式
        sheet.setTableStyle(createTableStyle());
        // 写入Excel中，也提供了多个重载方法，根据需要选择
        writer.write(excelParams.getData(), sheet);

        // 根据数据展示需要，用于合并单元格
        List<int[]> mergeList = excelParams.getMergeList();
        if (mergeList != null && mergeList.size() > 0){
            for (int[] arr : mergeList) {
                // 待合并的单元格参数：开始的行数，结束的行数，开始的列数，结束的列数
                writer.merge(arr[0], arr[1], arr[2], arr[3]);
            }
        }
        writer.finish();
        out.flush();
    }


    /**
     * 将文件输出到浏览器（导出文件）
     *
     * @param response 响应
     * @param typeEnum excel类型
     */
    private static void prepareResponds(HttpServletResponse response,ExcelTypeEnum typeEnum) throws UnsupportedEncodingException {

        String fileName = new String((new SimpleDateFormat("MMddHHmm").format(new Date()))
                .getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);
        response.setContentType("multipart/form-data");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + typeEnum.getValue());
    }


    /**
     * 表格样式：目前easyExcel的样式调整，仅支持表头和内容两部分别统一设置
     * @return
     */
    private static TableStyle createTableStyle(){
        TableStyle tableStyle = new TableStyle();
        tableStyle.setTableHeadBackGroundColor(IndexedColors.GREY_50_PERCENT);
        tableStyle.setTableContentBackGroundColor(IndexedColors.GREY_25_PERCENT);
        Font contentFont = new Font();
        contentFont.setFontName("黑体");
        contentFont.setFontHeightInPoints((short)12);
        tableStyle.setTableContentFont(contentFont);
        Font headFont = new Font();
        headFont.setFontName("黑体");
        headFont.setFontHeightInPoints((short)10);
        tableStyle.setTableHeadFont(headFont);
        return tableStyle;
    }

    /**
     * 编码文件名
     */
    public static String encodingFilename(String filename)
    {
        filename = UUID.randomUUID().toString() + "_" + filename + ".xlsx";
        return filename;
    }

    /**
     * 获取下载路径
     *
     * @param filename 文件名称
     */
    public static String getAbsoluteFile(String filename)
    {
        String downloadPath = RuoYiConfig.getDownloadPath() + filename;
        File desc = new File(downloadPath);
        if (!desc.getParentFile().exists())
        {
            desc.getParentFile().mkdirs();
        }
        return downloadPath;
    }


}
